package com.warehouse.management.connection;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerConnection {

    private String	       userName;
    private String	       password;
    private String	       dbName;
    private String	       server;

    private EntityManager	entityManager;
    private EntityManagerFactory entityManagerFactory;

    public String getUserName() {
	return userName;
    }

    public void setUserName(String userName) {
	this.userName = userName;
    }

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public String getDbName() {
	return dbName;
    }

    public void setDbName(String dbName) {
	this.dbName = dbName;
    }

    public String getServer() {
	return server;
    }

    public void setServer(String server) {
	this.server = server;
    }

    public EntityManagerConnection(String userName, String password,
	    String dbName, String server) {

	this.userName = userName;
	this.password = password;
	this.dbName = dbName;
	this.server = server;
    }

    public Map<String, String> getConnectionProperties(String userName,
	    String password) {
	Map<String, String> properties = new HashMap<String, String>();
	properties.put("javax.persistence.jdbc.user", userName);
	properties.put("javax.persistence.jdbc.password", password);

	return properties;
    }

    public Map<String, String> getConnectionProperties() {

	return getConnectionProperties(this.getUserName(), this.getPassword());
    }

    public EntityManager openConnection() {
	this.entityManagerFactory = Persistence.createEntityManagerFactory(
		getServer() + getDbName(), getConnectionProperties());
	this.entityManager = entityManagerFactory.createEntityManager();

	return entityManager;
    }

    public void closeConnection() {
	entityManager.close();
    }
}
